<template>
    <div>
        <!--  面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--  卡片视图区域 -->
        <el-card>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input placeholder="请输入搜索内容" v-model="queryInfo.query"
              clearable
              @clear="getUserList" >
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
            </el-col>
          </el-row>
          <!-- 列表用户区域-->
          <el-table :data="userList"
            stripe
            border>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="mobile" label="手机号"></el-table-column>
            <el-table-column prop="role_name" label="角色"></el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.u_state"
                  :inactive-value="1"
                  :active-value="0"
                  active-color="#13ce66"
                  inactive-color="#999999"
                  @change="userStateChanged(scope.row)" >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row.id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="small" @click="removeUserByid(scope.row.id)"></el-button>
                <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                  <el-button type="warning" icon="el-icon-setting" size="small" @click="setRole(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="queryInfo.page"
            :page-size="queryInfo.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="addDialogVisible"
          width="50%"
          @close="addDialogClosed" >
          <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
            <el-form-item label="用户账号" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="addForm.phone"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户的对话框 -->
        <el-dialog
          title="修改用户"
          :visible.sync="editDialogVisible"
          width="50%"
          @close="editDialogClosed" >
          <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="80px">
            <el-form-item label="用户账号">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="name">
              <el-input v-model="editForm.name"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog
          title="分配角色"
          :visible.sync="setRoleDialogVisible"
          width="50%"
          @close="setRoleDialogClosed" >
          <div>
            <p>当前的用户：{{userInfo.name}}</p>
            <p>当前的角色：{{userInfo.role_name}}</p>
            <p>
              分配新角色：
              <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
            </p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
import { getUserList, updateUserState, addUser, getUser, editUser, deleteUser, getRoles, setUserRole } from '../../api/user'
export default {
  data () {
    // 验证手机格式
    var checkPhone = (rule, value, cb) => {
      const regPhone = /^1[3456789]\d{9}$/
      if (regPhone.test(value)) {
        return cb()
      }
      cb(new Error('手机号码格式错误'))
    }
    return {
      queryInfo: {
        query: '',
        page: 1,
        pageSize: 5
      },
      userList: [],
      total: 0,
      // 控制用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        name: '',
        phone: ''
      },
      // 添加用户表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在6到10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在6到18个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {
      },
      editFormRules: {
        name: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      setRoleDialogVisible: false,
      userInfo: {},
      rolesList: [],
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    getUserList () {
      getUserList(this.queryInfo).then(response => {
        const { data } = response
        this.userList = data.data.users
        this.total = data.data.total
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.page = newPage
      this.getUserList()
    },
    async userStateChanged (userInfo) {
      updateUserState({ state: userInfo.u_state }).then(response => {
        this.$message.success('更新用户状态成功')
      }).catch(() => {
        userInfo.u_state = (userInfo.u_state === 0 ? 1 : 0)
        this.$message.error('更新用户状态失败')
      })
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        addUser(this.addForm).then(response => {
          this.addDialogVisible = false
          this.getUserList()
        }).catch(error => {
          this.$message.error(error.message)
        })
      })
    },
    async showEditDialog (id) {
      getUser(id).then(response => {
        const { data } = response
        this.editDialogVisible = true
        this.editForm = data.data
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        editUser(this.editForm.id, this.editForm).then(response => {
          this.editDialogVisible = false
          this.$message.success('修改成功')
          this.getUserList()
        }).catch(error => {
          this.$message.error(error.message)
        })
      })
    },
    async removeUserByid (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 确定返回confirm，取消返回 cancel
      if (confirmResult === 'confirm') {
        deleteUser(id).then(response => {
          this.$message.success('用户删除成功')
          this.getUserList()
        }).catch(error => {
          this.$message.error(error.message)
        })
      }
    },
    setRole (user) {
      this.userInfo = user
      if (this.rolesList.length === 0) {
        getRoles().then(response => {
          const { data } = response
          if (data.data) {
            this.rolesList = data.data
          }
        }).catch(error => {
          return this.$message.error(error.message)
        })
      }
      this.setRoleDialogVisible = true
    },
    setRoleDialogClosed () {
      this.selectedRoleId = ''
    },
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      setUserRole(this.userInfo.id, this.selectedRoleId).then(response => {
        this.$message.success('更新角色成功')
        this.getUserList()
        this.setRoleDialogVisible = false
      }).catch(error => {
        this.$message.error(error.message)
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
